<template>
  <div class="chat-group-users">
    <div style="margin-bottom: 0; padding: 10px; background: #f3f3f3">
      <div class="flex-row vertical-center">
        <i
          v-if="me && me.role > 0"
          class="el-icon-circle-plus-outline"
          title="添加成员"
          style="margin-right: 6px; color: #05b405; font-size: 1.2em; cursor: pointer"
          @click="showNewThread = true"></i>
        <span style="color: #595959">群成员({{ members.length }})</span>
        <i
          class="el-icon-search"
          style="margin-left: auto; font-size: 1.2em; cursor: pointer"
          :style="{ color: showSearch ? '#409eff' : '#aaa' }"
          @click="showSearch = !showSearch"></i>
      </div>
      <ElInput
        v-show="showSearch"
        v-model="query"
        placeholder="搜索群成员"
        size="mini"
        clearable
        suffix-icon="el-icon-search"
        style="margin-top: 8px" />
    </div>
    <CustomScrollbar class="chat-users">
      <ul>
        <li
          v-for="item in filteredUsers"
          :key="item.id"
          :class="['hover-active', { 'chat-ban': item.status === 1 }]"
          :title="item.status === 1 ? '已禁言' : ''"
          style="padding: 4px 8px"
          @contextmenu.prevent="e => showContextMenu(item, e)">
          <img class="avatar" :src="$withContext(item.member.avatar) || require('@/assets/images/avatar.png')" alt="" />
          <!--<span v-else class="avatar">{{ item.member.name.substr(0, 1) }}</span>-->
          {{ item.member.name }}
          <i
            v-if="[1, 100].includes(item.role)"
            :title="item.role === 100 ? '群主' : '管理员'"
            :style="{ color: item.role === 100 ? '#f1a72d' : '#bd7865' }"
            class="el-icon-user-solid"></i>
        </li>
        <li
          v-if="members.length && !filteredUsers.length"
          style="padding-top: 20px; color: #808080; text-align: center">
          无匹配结果
        </li>
        <li v-if="!members.length" style="padding-top: 20px; color: #808080; text-align: center">暂无数据</li>
      </ul>
    </CustomScrollbar>
    <ContextMenu ref="contextMenu" :list="roleMenu" @on-item-click="onMenuItemClick" />
    <UserPicker
      v-if="showNewThread"
      :visible.sync="showNewThread"
      :disabled-ids="members.map(value => value.member.userId)"
      multiple
      @confirm="onConfirm" />
  </div>
</template>

<script>
  import { addMember, getMembers, removeMember, toggleAdmin, toggleBan } from './api/group-member'
  import { mapMutations, mapState } from 'vuex'
  import message from '@/vue/mixin/message'
  import { newThread } from '@/components/im/api/thread'

  export default {
    name: 'ChatGroupUsers',
    mixins: [message],
    message: {
      addMember() {
        this.fetchData()
      },
      toggleBan() {
        this.fetchData()
      },
      toggleAdmin() {
        this.fetchData()
      },
      removeMember() {
        this.fetchData()
      }
    },
    props: {
      value: Object,
      session: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        members: [],
        contextMember: {},
        showNewThread: false,
        showSearch: false,
        query: ''
      }
    },
    computed: {
      ...mapState('im', ['chatWindowVisible']),
      ...mapState('user', {
        userId: state => state.sysUser.userId
      }),
      me() {
        return this.members.find(value => value.member.userId === this.userId)
      },
      roleMenu() {
        if (!this.me || !this.contextMember || this.contextMember === this.me) {
          return []
        }

        const menu = [
          {
            text: '发消息',
            action: 'chat',
            icon: 'el-icon-chat-line-square'
          }
        ]

        if (this.contextMember.role >= this.me.role) {
          return menu
        }

        if (this.me.role === 100) {
          if (this.contextMember.role < 1) {
            menu.push({
              text: '设为管理员',
              action: 'toggleAdmin',
              icon: 'el-icon-user-solid'
            })
          }
          if (this.contextMember.role === 1) {
            menu.push({
              text: '取消管理员',
              action: 'toggleAdmin',
              icon: 'el-icon-user-solid'
            })
          }
        }
        if (this.me.role > this.contextMember.role) {
          menu.push({
            text: '移出群聊',
            action: 'removeMember',
            icon: 'el-icon-circle-close'
          })
          if (this.contextMember.status === 0) {
            menu.push({
              text: '禁言',
              action: 'toggleBan',
              icon: 'el-icon-video-pause'
            })
          }
          if (this.contextMember.status === 1) {
            menu.push({
              text: '解除禁言',
              action: 'toggleBan',
              icon: 'el-icon-video-pause'
            })
          }
        }
        return menu
      },
      filteredUsers() {
        if (this.query) {
          return this.members.filter(value => value.member.name.indexOf(this.query) > -1)
        }
        return this.members
      }
    },
    watch: {
      'session.id': {
        immediate: true,
        handler: 'fetchData'
      },
      me(newVal) {
        this.$emit('input', newVal)
      }
    },
    methods: {
      ...mapMutations('im', ['setActiveThreadId']),
      async fetchData() {
        if (this.session.group?.id) {
          const res = await getMembers(this.session.group.id)
          this.members = this.sortMember(res.data.data)
        }
      },
      sortMember(groupMembers) {
        return groupMembers.sort((first, second) => {
          if (first.role === 100 && second.role === 100) {
            return first.member.name.localeCompare(second.member.name, 'zh-CN')
          } else if (first.role === 100) {
            return -1
          } else if (second.role === 100 && first.role !== 100) {
            return 1
          } else if (first.role === 1 && second.role === 1) {
            return first.member.name.localeCompare(second.member.name, 'zh-CN')
          } else if (first.role === 1) {
            return -1
          } else if (second.role === 1 && first.role !== 1) {
            return 1
          } else {
            return first.member.name.localeCompare(second.member.name, 'zh-CN')
          }
        })
      },
      showContextMenu(item, e) {
        this.contextMember = item
        this.$refs.contextMenu.show(e)
      },
      async onMenuItemClick(item) {
        await this[item.action]?.(this.contextMember)
        this.contextMember = {}
      },
      async toggleAdmin(groupMember) {
        await this.$confirm(
          groupMember.role === 0
            ? `您确定要将[${groupMember.member.name}]设置为管理员吗？`
            : `您确定要移除[${groupMember.member.name}]的管理员权限吗？`,
          { type: 'warning' }
        )
        await toggleAdmin(groupMember.group.id, groupMember.id)
        groupMember.role = groupMember.role === 0 ? 1 : 0
        this.members = this.sortMember(this.members)
      },
      async toggleBan(groupMember) {
        await this.$confirm(`您确定要将[${groupMember.member.name}]禁言吗？`, { type: 'warning' })
        await toggleBan(groupMember.group.id, groupMember.id)
        groupMember.status = groupMember.status === 0 ? 1 : 0
        this.members = this.sortMember(this.members)
      },
      async removeMember(groupMember) {
        await this.$confirm(`您确定要将[${groupMember.member.name}]移除该群聊吗？`, { type: 'warning' })
        await removeMember(groupMember.group.id, groupMember.id)
        this.members = this.members.filter(value => value.id !== groupMember.id)
      },
      async onConfirm(users) {
        const loading = this.$loading({ text: '处理中...', background: 'rgba(0,0,0,0.2)' })
        try {
          await addMember(
            this.session.group.id,
            users.map(value => value.id)
          )
          await this.fetchData()
        } catch (e) {}
        loading.close()
      },
      async chat(item) {
        const res = await newThread({ userIds: [item.member.userId], type: 'p2p' })
        this.setActiveThreadId(res.data.data.id)
      }
    }
  }
</script>

<style lang="scss">
  .chat-group-users {
    @include flex-item;
    @include flex-column;
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;

    .chat-ban {
      color: #ccc;
    }

    .avatar {
      display: inline-block;
      width: 18px;
      height: 18px;
      margin-right: 4px;
      color: #fff;
      font-weight: bold;
      font-size: 12px;
      line-height: 18px;
      text-align: center;
      vertical-align: middle;
      background: #9aa5c3;
      border-radius: 50%;
    }

    .chat-users {
      @include flex-item;
    }
  }
</style>
